import zsh.service.IService;
import zsh.service.ServiceImpl;
import com.alibaba.fastjson2.JSONObject;
import domain.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/addStudent")
public class AddStudent extends HttpServlet {
        private IService studentService = new ServiceImpl();

        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // 解决乱码问题
            req.setCharacterEncoding("utf-8");
            // 解析请求体中的参数
            // 1. 获取输入流
            BufferedReader reader = req.getReader();
            // 2. 获取请求的完整信息
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            // 3, 将字符串信息解析承json对象
            Student student = JSONObject.parseObject(sb.toString(), Student.class);

            // 二、进行业务逻辑处理
            try {
                studentService.addStudent(student);
                resp.setStatus(HttpServletResponse.SC_CREATED); // 201 Created
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

